// pages/mine/mine.js
const app = getApp(),
  globalData = app.globalData,
  api = require('../../api/index'),
  utils = require('../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    informImg:globalData.pictureRouting+'myBackgroundpicture.png',
    feiImg:globalData.pictureRouting+'consumption_icon.png',
    tiImg:globalData.pictureRouting+'MoneyBackgroundIcon.png',
    daifukImg:globalData.pictureRouting+'daifukuan_icon.png',
    daifahuoImg:globalData.pictureRouting+'daifahuo_icon.png',
    daishouhuoImg:globalData.pictureRouting+'daishouhuo_icon.png',
    yiwanchengImg:globalData.pictureRouting+'yiwancheng_icon.png',
    tuiShouImg:globalData.pictureRouting+'tuiguanhuoshouhou_icon.png',
    kucunImg:globalData.pictureRouting+'wodekucun_icon.png',
    zitiIMg:globalData.pictureRouting+'wodeziti_icon.png',
    buhuoImg:globalData.pictureRouting+'wodebuhuo_icon.png',
    tuanduiguanImg:globalData.pictureRouting+'tuanduiguanli_icon.png',
    kanjiaImg:globalData.pictureRouting+'wodekanjia_icon.png',
    tuangouImg:globalData.pictureRouting+'wodetuandui_icon.png',
    ypuhuiqImg:globalData.pictureRouting+'youhuiquan_icon.png',
    kefuImg:globalData.pictureRouting+'kehuzhongx_icon.png',
    gunayuImg:globalData.pictureRouting+'guanyuwomen_icon.png',
    tuichuImg:globalData.pictureRouting+'tuicudenglu_icon.png',
    loading: false,
    toast: {
      visible: false,
      text: ''
    },
    userInfo: {},
    agentInfo: {}, // 是否代理商的信息
    agentLoading: false,
    imageBaseUri: globalData.isDev ? 'http://47.114.5.153:8082' : globalData.imageBaseUri,
    status: 0,
    canIUseGetUserProfile: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(this.data.userInfo, 'userInfo')
    if (wx.getUserProfile) {
      console.log('111')
      this.setData({
        canIUseGetUserProfile: true
      })
    } else {
      console.log('222')
    }
    this.reload()
  },

  onPullDownRefresh: function () {
    this.reload()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.reload()
  },

  reload() {
    this.setData({
      userInfo: wx.getStorageSync('userinfo') || {},
      status: 2
    })

    console.log(this.data.userInfo, 'userInfo')
    if (this.data.userInfo.AccessToken) {
      this.getBalance();
      this.getUser();
      this.getBenefits();
    }
    if (this.data.agentInfo && this.data.agentInfo.MemberGradeId) {
      this.getBenefits();
    }
  },

  toMyIncome() {
    wx.navigateTo({
      url: '/pages/mine/myIncome/myIncome',
    })
  },

  toCoupon() {
    wx.navigateTo({
      url: '/pages/mine/coupon/moreList/moreList',
    })
  },

  async toMyOrder() {
    // 订阅下级支付成功通知
    await utils.subscribe('cTHEhOYPqcC693tSzZ_1MTbixtbKbXmrL2aGhzMrviw');

    wx.navigateTo({
      url: '/pages/mine/myOrder/myOrder',
    })
  },

  toApply() {
    wx.navigateTo({
      url: `/pages/mine/myStock/myStock?tab=1`,
    })
    // wx.navigateTo({
    //   url: `/pages/product/detail/detail?id=2008291227289650512`,
    // })
    // wx.switchTab({
    //   url: '/pages/index/index',
    // })
  },

  toAddress() {
    wx.navigateTo({
      url: '/pages/product/address/address',
    })
  },

  toCart() {
    wx.switchTab({
      url: '/pages/car/car',
    })
  },

  toAgreement() {
    wx.navigateTo({
      url: '/pages/mine/agreements/agreements',
    })
  },

  getUserProfile(e) {
    console.log(e, '获取用户信息2')
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于下单购买商品', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res, '登录profile返回的res')
        let user = res.userInfo;
        let obj = {
          nickname: user.nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "*"),
          province: user.province,
          sex: user.gender,
          city: user.city,
          country: user.country,
          headimgurl: user.avatarUrl,
          unionid: '',
          code: res.code || ''
        }

        wx.login({
          success: res => {
            console.log('wx.login', res)
            this.setData({
              loading: true
            })
            try {
              api.base.wxOnLogin(Object.assign(obj, { code: res.code })).then(res => {
                console.log(res, '登录结果')
                let token = res.data.ResData.AccessToken || '',
                  userinfo = res.data.ResData || {};

                this.setData({
                  userInfo: res.data.ResData || {},
                  loading: false
                })

                //token
                wx.setStorageSync('token', token);
                // app.globalData.authToken = token;

                //存放用户信息
                wx.setStorageSync('userinfo', userinfo);
                app.globalData.userInfo = userinfo;

                // 存放sessionId
                wx.setStorageSync('ssId', userinfo.WxSessionId);
                app.globalData.ssId = userinfo.WxSessionId;
                this.reload();
              })
            } catch (e) {
              this.setData({
                loading: false
              })
            }
          }
        })
      }
    })
  },

  async getUserInfo(res) {
    console.log(res, '获取用户信息1')
    // wx.navigateTo({
    //   url: '/pages/login/login',
    // })
    if (res.detail) {
      let user = res.detail.userInfo;
      let obj = {
        nickname: user.nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "*"),
        province: user.province,
        sex: user.gender,
        city: user.city,
        country: user.country,
        headimgurl: user.avatarUrl,
        unionid: '',
      }

      wx.login({
        success: res => {
          console.log('wx.login', res)
          this.setData({
            loading: true
          })
          try {
            api.base.wxOnLogin(Object.assign(obj, { code: res.code })).then(res => {
              console.log(res, '登录结果')
              let token = res.data.ResData.AccessToken || '',
                userinfo = res.data.ResData || {};

              this.setData({
                userInfo: res.data.ResData || {},
                loading: false
              })

              //token
              wx.setStorageSync('token', token);
              // app.globalData.authToken = token;

              //存放用户信息
              wx.setStorageSync('userinfo', userinfo);
              app.globalData.userInfo = userinfo;

              // 存放sessionId
              wx.setStorageSync('ssId', userinfo.WxSessionId);
              app.globalData.ssId = userinfo.WxSessionId;
              this.reload();
            })
          } catch (e) {
            this.setData({
              loading: false
            })
          }
        }
      })
    }

  },

  copy(e) {
    utils.copy(e.currentTarget.dataset.id)
  },

  logout() {
    wx.clearStorageSync();
    this.setData({
      toast: {
        visible: true,
        text: '退出登录成功'
      },
      userInfo: {},
      agentInfo: {}
    })
    globalData.authToken = ''
    // wx.switchTab({
    //   url: '/pages/index/index',
    // })
  },

  // 获取我的收益
  async getBenefits() {
    try {
      let res = await api.balance.getMyBenefits(),
        data = res.data.ResData || {};
      this.setData({
        status: 2,
        pageData: data
      })
      console.log(res, '我的收益')
    } catch (e) {
      this.setData({
        status: 1
      })
      console.log(e, '获取我的收益失败')
    }
  },

  // 获取我的可提现金额
  async getBalance() {
    try {
      let res = await api.balance.getMyBalance(),
        data = res.data.ResData || 0;
      this.setData({
        status: 2,
        balance: data
      })
      console.log(res, '可提现金额')
    } catch (e) {
      this.setData({
        status: 1
      })
      console.log(e, '获取可提现金额失败')
    }
  },

  // 登录后获取用户等级信息
  async getUser() {
    this.setData({
      agentLoading: true
    })
    try {
      let res = await api.user.getUser(),
        data = res.data.ResData || {};
      this.setData({
        agentInfo: data,
        agentLoading: false,
        status: 2
      })
      wx.setStorageSync('agentInfo', data)
      console.log(res, '获取用户等级信息')
    } catch (e) {
      console.log(e, '获取用户等级信息失败')
      this.setData({
        agentLoading: false,
        toast: {
          visible: true,
          text: e.data.ErrMsg
        },
        status: 1
      })
    }
  },
  gotoScan() {
    wx.navigateTo({ url: '/pages/scan/scan' });
  },

  toMember () {
    wx.navigateTo({
      url: '/pages/mine/members/members',
    })
  },

  toStock() {
    wx.navigateTo({
      url: `/pages/mine/myStock/myStock?tab=0`,
    })
  },

  /**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {
		let userId = globalData.userInfo.UserId || '';
		console.log(`/pages/index/index?userId=${userId}`, '首页分享链接')
		return {
			title: 'TNTB超多好货等你来看',
			path: `/pages/index/index?userId=${userId}`,
			imageUrl: 'https://xhbehappy.cn/upload/2020082617112274177259.jpg'
		}
  },
  
  toSpread() {
		wx.navigateTo({
			url: '/pages/mine/spread/spread',
		})
	},

	toGuide() {
		wx.navigateTo({
			url: '/pages/mine/guide/guide',
		})
	},

})